package com.hnhegui.backend.system.service;

import com.hnhegui.backend.entity.PageResult;
import com.hnhegui.backend.system.dto.request.UserQueryRequestDTO;
import com.hnhegui.backend.system.dto.response.UserResponseDTO;
import com.hnhegui.backend.system.entity.User;
import com.hnhegui.backend.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public PageResult<UserResponseDTO> queryUsers(UserQueryRequestDTO request) {
        // 参数校验与默认值设置
        if (request.getPage() == null || request.getPage() < 1) {
            request.setPage(1);
        }
        if (request.getPageSize() == null || request.getPageSize() < 1 || request.getPageSize() > 100) {
            request.setPageSize(20);
        }

        // 计算分页偏移量
        Integer offset = (request.getPage() - 1) * request.getPageSize();
        Integer limit = request.getPageSize();

        // 查询总记录数
        Long total = userMapper.countUsers(
                request.getUsername(),
                request.getPhone(),
                request.getStatus(),
                request.getRole(),
                request.getStartTime(),
                request.getEndTime()
        );

        // 如果总记录数为0，直接返回空结果
        if (total == 0) {
            return new PageResult<>(0L, new ArrayList<>());
        }

        // 查询用户列表
        List<User> users = userMapper.searchUsers(
                request.getUsername(),
                request.getPhone(),
                request.getStatus(),
                request.getRole(),
                request.getStartTime(),
                request.getEndTime(),
                offset,
                limit
        );

        // 数据脱敏：转换为UserResponse（排除password字段）
        List<UserResponseDTO> userResponses = users.stream()
                .map(this::convertToUserResponse)
                .collect(Collectors.toList());

        // 构建分页结果
        return new PageResult<>(total, userResponses);
    }

    /**
     * 将User实体转换为UserResponse（数据脱敏）
     *
     * @param user 用户实体
     * @return 用户响应DTO
     */
    private UserResponseDTO convertToUserResponse(User user) {
        UserResponseDTO response = new UserResponseDTO();

        // 复制除password外的所有字段
        response.setUserId(user.getUserId());
        response.setUsername(user.getUsername());
        response.setPhone(user.getPhone());
        response.setEmail(user.getEmail());
        response.setRole(user.getRole() != null ? user.getRole().name() : null);
        response.setStatus(user.getStatus());
        response.setCreateTime(user.getCreateTime());
        response.setUpdateTime(user.getUpdateTime());

        return response;
    }

    /**
     * 根据用户名查询用户
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /**
     * 根据手机号查询用户
     */
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    /**
     * 根据用户ID查询用户
     */
    public User findById(Long userId) {
        return userMapper.findById(userId);
    }

    /**
     * 插入用户
     */
    public int insert(User user) {
        return userMapper.insert(user);
    }

    /**
     * 更新用户
     */
    public int update(User user) {
        return userMapper.update(user);
    }
}
